package com.jjb.www.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.animation.AnimationUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.view.ShapeButton;
import com.hjq.widget.view.CountdownView;
import com.jjb.www.R;
import com.jjb.www.aop.Log;
import com.jjb.www.aop.SingleClick;
import com.jjb.www.app.AppActivity;
import com.jjb.www.http.api.GetCodeApi;
import com.jjb.www.http.api.LoginApi;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.http.model.HttpListData;
import com.jjb.www.manager.InputTextManager;
import com.jjb.www.manager.IntentKey;
import com.jjb.www.other.AppConfig;
import com.jjb.www.other.KeyboardWatcher;
import com.hjq.http.EasyConfig;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.Platform;
import com.hjq.umeng.UmengClient;
import com.hjq.umeng.UmengLogin;

/**
 *    author : Android CRG
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2018/10/18
 *    desc   : 登录界面
 */
public final class LoginActivity extends AppActivity
        implements UmengLogin.OnLoginListener
{

    private static final String INTENT_KEY_IN_PHONE = "phone";
    private static final String INTENT_KEY_IN_PASSWORD = "password";

    @Log
    public static void start(Context context, String phone, String password) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(INTENT_KEY_IN_PHONE, phone);
        intent.putExtra(INTENT_KEY_IN_PASSWORD, password);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private AppCompatEditText mEtVerificationPhone;
    private CountdownView mCvLoginCountdown;
    private AppCompatEditText mEtVerificationCode;
    private ShapeButton mBtnLogin;
    private ShapeLinearLayout mLlWx;
    private ShapeLinearLayout mLlPhone;
    private static final String SECRET_KEY = "cqsjjb!@#&2022GO";
    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;
    }

    @Override
    protected void initView() {
        mEtVerificationPhone = findViewById(R.id.et_verification_phone);
        mCvLoginCountdown = findViewById(R.id.cv_login_countdown);
        mEtVerificationCode = findViewById(R.id.et_verification_code);
        mBtnLogin = findViewById(R.id.btn_login);
        mLlWx = findViewById(R.id.ll_wx);
        mLlPhone = findViewById(R.id.ll_phone);
        setOnClickListener(mBtnLogin,mLlWx,mLlPhone,mCvLoginCountdown);

        InputTextManager.with(this)
                .addView(mEtVerificationPhone)
                .addView(mEtVerificationCode)
                .setMain(mBtnLogin)
                .setAlpha(true)
                .build();
    }

    @Override
    protected void initData() {
        // 判断用户当前有没有安装微信
        if (!UmengClient.isAppInstalled(this, Platform.WECHAT)) {
            mLlWx.setVisibility(View.GONE);
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {

        if (view == mBtnLogin) {
            if (mEtVerificationPhone.getText().toString().length() != 11) {
                mEtVerificationPhone.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shake_anim));
                toast(R.string.common_phone_input_error);
                return;
            }
            if (mEtVerificationCode.getText().toString().length() != 4) {
                mEtVerificationCode.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shake_anim));
                toast(R.string.common_code_input_hint);
                return;
            }
            // 隐藏软键盘
            hideKeyboard(getCurrentFocus());
            EasyHttp.post(this)
                    .api(new LoginApi()
                            .setMobile(mEtVerificationPhone.getText().toString())
                    .setCode(mEtVerificationCode.getText().toString())
                    .setType("2"))
                    .request(new HttpCallback<HttpData<LoginApi.Bean>>(this) {

                        @Override
                        public void onSucceed(HttpData<LoginApi.Bean> data) {
                            EasyConfig.getInstance().addParam(IntentKey.TOKEN, data.getData().getToken());
                            AppConfig.getInstance().setToken(data.getData().getToken());
                            AppConfig.getInstance().setUserBean(data.getData());
                            startActivity(HomeActivity.class);
                            finish();
                        }
                    });
        }else if (view == mLlWx) {
            toast("记得改好第三方 AppID 和 Secret，否则会调不起来哦");
            Platform platform;
            platform = Platform.WECHAT;
            UmengClient.login(this, platform, this);
        }else if (view==mCvLoginCountdown){
            if (mEtVerificationPhone.getText().toString().length() != 11) {
                mEtVerificationPhone.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shake_anim));
                toast(R.string.common_phone_input_error);
                return;
            }

            // 隐藏软键盘
            hideKeyboard(getCurrentFocus());

            EasyHttp.post(this)
                    .api(new GetCodeApi()
                            .setMobile(mEtVerificationPhone.getText().toString()))
                    .request(new HttpCallback<HttpListData<Void>>(this) {

                        @Override
                        public void onSucceed(HttpListData<Void> data) {
                            toast(R.string.common_code_send_hint);
                            mCvLoginCountdown.start();
                        }
                    });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }

    /**
     * {@link UmengLogin.OnLoginListener}
     */

    /**
     * 授权成功的回调
     *
     * @param platform      平台名称
     * @param data          用户资料返回
     */
    @Override
    public void onSucceed(Platform platform, UmengLogin.LoginData data) {
        if (isFinishing() || isDestroyed()) {
            // Glide：You cannot start a load for a destroyed activity
            return;
        }

        // 判断第三方登录的平台
        switch (platform) {
            case QQ:
                break;
            case WECHAT:
                break;
            default:
                break;
        }

//        GlideApp.with(this)
//                .load(data.getAvatar())
//                .circleCrop()
//                .into(mLogoView);

        toast("昵称：" + data.getName() + "\n" +
                "性别：" + data.getSex() + "\n" +
                "id：" + data.getId() + "\n" +
                "token：" + data.getToken());
    }

    /**
     * 授权失败的回调
     *
     * @param platform      平台名称
     * @param t             错误原因
     */
    @Override
    public void onError(Platform platform, Throwable t) {
        toast("第三方登录出错：" + t.getMessage());
    }

    /**
     * {@link KeyboardWatcher.SoftKeyboardStateListener}
     */

    @NonNull
    @Override
    protected ImmersionBar createStatusBarConfig() {
        return super.createStatusBarConfig()
                // 指定导航栏背景颜色
                .navigationBarColor(R.color.white);
    }
}